<template>
  <div class="container">
    <div class="app-container">
      <!-- 卡片 -->
      <el-card shadow="never">
        <!-- 表单 -->
        <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="width:100%" label-width="80px">
          <el-row class="xwel-row">
            <el-col :span="6">
              <el-form-item label="标签名称">
                <el-input v-model="searchForm.tags" placeholder="请输入" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="城市">
                <el-select v-model="searchForm.province" placeholder="请选择" style="width:100%" @change="onchange">
                  <el-option v-for="item in cityProper" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="地区">
                <el-select v-model="searchForm.city" placeholder="请选择" style="width:100%">
                  <el-option v-for="item in county" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input v-model="searchForm.shortName" style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="xwel-row">
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="searchForm.state" placeholder="请选择" style="width:100%">
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="last-col">
              <el-button size="small" @click="clearForm">清除</el-button>
              <el-button type="primary" size="small" @click="searchBtn">搜索</el-button>
            </el-col>
            <el-col :span="12" style="text-align: right;">
              <el-button type="success" size="small" @click="addCompany">
                <i class="el-icon-edit" />
                新增用户
              </el-button>
            </el-col>
          </el-row>
        </el-form>
        <!-- 总条数提示 -->
        <el-alert
          :title="`共 ${counts} 条记录`"
          type="info"
          show-icon
          :closable="false"
        />
        <!-- 表格 -->
        <el-table
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          :header-cell-style="{
            background:'#fafafa',height:'45px',color:'#909399',borderBottom:'2px solid #e8e8e8'}"
        >
          <el-table-column align="center" label="序号" prop="id" />
          <el-table-column align="center" label="企业编号" prop="number" />
          <el-table-column align="center" label="企业简称" prop="shortName" />
          <el-table-column align="left" label="标签" prop="tags" />
          <el-table-column align="center" label="创建者" prop="creatorID">
            <template v-slot="{row}">
              {{ replayName(row.creatorID) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建日期" prop="addDate">
            <template v-slot="{row}">{{ row.addDate|formatDate('yyyy-MM-dd') }}</template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remarks" />
          <el-table-column :formatter="formatter" align="center" label="状态" prop="state" />
          <el-table-column align="center" label="操作" prop="name" width="180px">
            <template v-slot="{row}">
              <el-button circle icon="el-icon-edit" plain type="primary" @click="editCompany(row.id)" />
              <el-tooltip effect="dark" placement="top">
                <template #content>{{ row.state === 1 ? '禁用' : '启用' }}</template>
                <el-button :type="row.state === 1 ? 'warning' : 'success' " circle plain @click="disabledCompany(row)">
                  <i :class="row.state === 1 ? 'el-icon-close' : 'el-icon-check'" />
                </el-button>
              </el-tooltip>
              <el-button circle icon="el-icon-delete" plain type="danger" @click="deleteCompany(row.id)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row align="middle" type="flex">
          <el-col class="PageTool" style="text-align: right;">
            <PageTool :pagination-page="page.page" :pagination-pagesize="page.pagesize" :total="counts" @pageChange="changepage" @pageSizeChange="changepagesizes" />
          </el-col>
        </el-row>
      </el-card>
      <!-- 弹出层 -->
      <CompanysAdd ref="CompanysAdd" :show-dialog.sync="showDialog" @updateList="list" />
    </div>
  </div>
</template>

<script>
import PageTool from '@/module-hmmm/components/pageTool'
import CompanysAdd from '@/module-hmmm/components/companys-add'
import { list, remove, disabled } from '@/api/hmmm/companys'
import { status } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { list as userListApi } from '@/api/base/users'
export default {
  components: {
    PageTool,
    CompanysAdd
  },
  data() {
    return {
      searchForm: {
        tags: '', // 方向（企业标签）
        province: '', // 北京市
        city: '', // 朝阳区
        shortName: '', // 企业名称
        state: ''
      },
      tableData: [],
      search: '',
      showDialog: false,
      CompanyId: '',
      details: {},
      counts: 0,
      text: '',
      message: '',
      cityProper: [],
      county: [],
      page: {
        page: 1,
        pagesize: 10
      },
      loading: false,
      newObj: {},
      userList: []
    }
  },
  created() {
    this.list()
    const cityProper = provinces()
    this.cityProper = cityProper
    this.getuserList()
  },
  methods: {
    replayName(id) {
      const arr = this.userList.filter(item => item.id === id)
      return arr?.[0]?.username
    },
    async getuserList() {
      const { data: { list }} = await userListApi()
      this.userList = list
    },
    // 改变页码
    async changepage(pagenum) {
      this.page.page = pagenum
      for (const i in this.searchForm) {
        if (this.searchForm[i] !== '') {
          this.newObj[i] = this.searchForm[i]
          this.page.page = 1
        }
      }
      const { data } = await list({ ...this.page, ...this.newObj })
      this.tableData = data.items
      this.newObj = {}
    },
    // 改变每页条数
    changepagesizes(sizes) {
      this.page.pagesize = sizes
      this.page.page = 1
      this.list()
    },
    async list() {
      //   请求列表
      const { data } = await list(this.page)
      this.tableData = data.items
      //   获取总条数
      this.counts = data.counts
    },
    // 格式化状态
    formatter(row) {
      const obj = status.find((item) => item.value === row.state)
      return obj ? obj.label : '未知'
    },
    // 显示弹窗
    addCompany() {
      this.showDialog = true
    },
    // 编辑
    editCompany(id) {
      this.showDialog = true
      this.$refs.CompanysAdd.detailsCompany(id)
    },
    // 删除
    deleteCompany(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await remove({ id })
          this.$message.success('删除成功!')
          this.page.page = Math.ceil((this.counts - 1) / this.page.pagesize)
          this.list()
        })
        .catch(() => {
          this.$message.info('已取消操作！')
        })
    },
    // 禁用
    disabledCompany(row) {
      this.$confirm(`已成功${row.state === 1 ? '禁用' : '启用'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.state === 1) {
            // 做禁用操作
            await disabled({ id: row.id, state: 0 })
            this.message = '已成功禁用'
          } else if (row.state === 0) {
            // 做启用操作
            await disabled({ id: row.id, state: 1 })
            this.message = '已成功启用'
          }
          this.$message({
            type: 'success',
            message: this.message
          })
          this.searchBtn()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    onchange(city) {
      const county = citys(city)
      this.county = county
      this.searchForm.city = county[0]
    },
    // /搜索 /
    async searchBtn() {
      for (const i in this.searchForm) {
        if (this.searchForm[i] !== '') {
          this.newObj[i] = this.searchForm[i]
        }
      }
      const { data } = await list({ ...this.page, ...this.newObj })
      this.counts = data.counts
      this.tableData = data.items
      this.newObj = {}
    },
    clearForm() {
      this.searchForm = {
        tags: '', // 方向（企业标签）
        province: '', // 北京市
        city: '', // 朝阳区
        shortName: '', // 企业名称
        state: ''
      }
      this.newObj = {}
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
    .el-form-item {
        width: 100%;
        display: flex;
        .el-form-item__content {
            flex: 1;
        }
    }
}

.text {
    font-size: 14px;
}

.item {
    padding: 20px;
}

.box-card {
    width: 480px;
    margin: 20px;
}
.last-col {
    padding-left: 40px;
}
.el-alert {
    margin-bottom: 20px;
}
.PageTool {
    margin-top: 20px;
}
</style>
